open Constant

let main opt_temporary =
	let temporary =
		match opt_temporary with
		| None -> 
			  begin match Ihm.ask_for_file() with
				|  None -> exit 1 
				| Some f -> f
				 end 
		| Some f -> f in
	if not (Sys.is_directory temporary) then exit 1;
	let model = new Model.model temporary in
	let ihm = new Ihm.ihm () in
	
	let update_camera_name () =
		ihm#set_camera_name_left model#camera_left;
		ihm#set_camera_name_right model#camera_right in
	
	let update_left () = ihm#set_left (model#left) in
	let update_right () = ihm#set_right (model#right) in
	let update () = update_left(); update_right() in
	
	let take_picture_callback action = 
		begin match action with
		| S_BOTH  -> model#take_both; Gc.full_major(); update()
		| S_LEFT  -> ihm#set_camera_busy_left true; model#take_photo_left; update_left()
		| S_RIGHT -> ihm#set_camera_busy_right true; model#take_photo_right; update_right()
		end;
		let i,l = model#position in 
		ihm#set_progress i (max 1 l) (fun () -> ())	in

	ihm#take_picture take_picture_callback;
	
	let move_callback ev =
		begin match ev with
			| PREV  -> model#previous
			| NEXT  -> model#next
			| START -> model#to_start
			| END   -> model#to_end
			| _     -> ()
		end;
		let i,l = model#position in ihm#set_progress i (max 1 l) update in 
	
	ihm#move move_callback;

	let save () = 
		try 
			model#save;
			ihm#tell "Save done"
		with Failure f -> ihm#tell ("Failure during save " ^ f) in
		
  let download_all () =
		 let final_kont nok =
		   begin try model#save
		   with Failure f -> ihm#tell ("Failure during save " ^ f) end; 
			 let message = 
			 	 if nok = 0 then "Download done" 
			   else "Download failed :" ^ string_of_int nok ^ " pictures missing." in 
		   ihm#tell message in
		 model#download_all ihm#set_progress final_kont in
	ihm#set_menu "_File"
		[("Save", save , Some GdkKeysyms._S) ;
		 ("Swap cameras", (fun () -> model#swap_cameras; ihm#swap_cameras; update_camera_name()), Some GdkKeysyms._X);
		 ("Quit", (fun () -> ihm#quit), Some GdkKeysyms._Q)];
	
	ihm#set_menu "_Entries"
		[("Insert", (fun () -> model#insert; update()), Some GdkKeysyms._I);
		("Delete", (fun () -> let a : bool = model#delete in update()), Some GdkKeysyms._D);
		("Download", download_all, Some GdkKeysyms._L);
		("Remove All", (fun () -> ihm#tell (if model#wipe_all then "SD Cards cleaned" else "Remove all failed")), Some GdkKeysyms._R) ];
	begin match model#get_focus_left with Some quad -> ihm#set_focus_info_left quad | None -> () end;
	begin match model#get_focus_right with Some quad -> ihm#set_focus_info_right quad | None -> () end;
	ihm#set_focus_callback_left model#focus_left;
	ihm#set_focus_callback_right model#focus_right;
	
	ihm#show;
	update();
	update_camera_name();
	
	GtkThread.main ();
	
	while true do () done